/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package njci.softerware.com.myexpress2017.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import njci.softerware.com.myexpress2017.R;
import njci.softerware.com.myexpress2017.http.HttpClient;
import njci.softerware.com.myexpress2017.http.HttpResponseHandler;
import njci.softerware.com.myexpress2017.serviceObj.dao.SharedPreferences;
import njci.softerware.com.myexpress2017.utils.Constant;
import njci.softerware.com.myexpress2017.zxing.ScanListener;
import njci.softerware.com.myexpress2017.zxing.ScanManager;
import njci.softerware.com.myexpress2017.zxing.decode.DecodeThread;
import njci.softerware.com.myexpress2017.zxing.decode.Utils;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 二维码扫描使用
 *
 * @author 刘红亮  2015年4月29日  下午5:49:45
 */
public final class CommonScanActivity extends Activity implements ScanListener, View.OnClickListener {
    static final String TAG = CommonScanActivity.class.getSimpleName();
    SurfaceView scanPreview = null;
    View scanContainer;
    View scanCropView;
    ImageView scanLine;
    ScanManager scanManager;
    TextView iv_light;
    TextView qrcode_g_gallery;
    TextView qrcode_ic_back;
    final int PHOTOREQUESTCODE = 1111;
    private String actionName = null;

    @Bind(R.id.service_register_rescan)
    Button rescan;
    @Bind(R.id.scan_image)
    ImageView scan_image;
    @Bind(R.id.authorize_return)
    ImageView authorize_return;
    private int scanMode;//扫描模型（条形，二维码，全部）

    @Bind(R.id.common_title_TV_center)
    TextView title;
    @Bind(R.id.scan_hint)
    TextView scan_hint;
    @Bind(R.id.tv_scan_result)
    TextView tv_scan_result;


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_scan_code);
        ButterKnife.bind(this);
        scanMode = getIntent().getIntExtra(Constant.REQUEST_SCAN_MODE, Constant.REQUEST_SCAN_MODE_ALL_MODE);
        int postTYpe = getIntent().getExtras().getInt(Constant.POST_SIGALE);
        if (postTYpe == 0) {
            actionName = "insertPackageInfo";
        } else if (postTYpe == 1) {
            actionName = "updatePackageInfo";
        } else if (postTYpe == 2) {
            actionName = "signPackageInfo";
        }
        initView();
    }

    void initView() {
        switch (scanMode) {
            case DecodeThread.BARCODE_MODE:
                title.setText(R.string.scan_barcode_title);
                scan_hint.setText(R.string.scan_barcode_hint);
                break;
            case DecodeThread.QRCODE_MODE:
                title.setText(R.string.scan_qrcode_title);
                scan_hint.setText(R.string.scan_qrcode_hint);
                break;
            case DecodeThread.ALL_MODE:
                title.setText(R.string.scan_allcode_title);
                scan_hint.setText(R.string.scan_allcode_hint);
                break;
        }
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        qrcode_g_gallery = (TextView) findViewById(R.id.qrcode_g_gallery);
        qrcode_g_gallery.setOnClickListener(this);
        qrcode_ic_back = (TextView) findViewById(R.id.qrcode_ic_back);
        qrcode_ic_back.setOnClickListener(this);
        iv_light = (TextView) findViewById(R.id.iv_light);
        iv_light.setOnClickListener(this);
        rescan.setOnClickListener(this);
        authorize_return.setOnClickListener(this);
        //构造出扫描管理器
        scanManager = new ScanManager(this, scanPreview, scanContainer, scanCropView, scanLine, scanMode, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        scanManager.onResume();
        rescan.setVisibility(View.INVISIBLE);
        scan_image.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        scanManager.onPause();
    }

    /**
     *
     */
    public void scanResult(Result rawResult, Bundle bundle) {
        //扫描成功后，扫描器不会再连续扫描，如需连续扫描，调用reScan()方法。
        //scanManager.reScan();
//		Toast.makeText(that, "result="+rawResult.getText(), Toast.LENGTH_LONG).show();

        if (!scanManager.isScanning()) { //如果当前不是在扫描状态
            //设置再次扫描按钮出现
            rescan.setVisibility(View.VISIBLE);
            scan_image.setVisibility(View.VISIBLE);
            Bitmap barcode = null;
            byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
            if (compressedBitmap != null) {
                barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
                barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
            }
            scan_image.setImageBitmap(barcode);
        }
        rescan.setVisibility(View.VISIBLE);
        scan_image.setVisibility(View.VISIBLE);
        tv_scan_result.setVisibility(View.VISIBLE);
        tv_scan_result.setText("结果是：" + rawResult.getText());
        String result = rawResult.getText();
        result = result.replace("*", "");
        SharedPreferences sh = SharedPreferences.getInstance();
        Integer peopleId = sh.getInt("userId", 0);
        postPackage(result, peopleId.toString());
    }

    public void postPackage(final String sn, final String peopleId) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String url = "http://127.0.0.1:8080/GameService/";
//                String action = "insertPackageInfo";
//                url = url + action;
//                Response response = null;
//                try {
//                    OkHttpClient client = new OkHttpClient();
//                    String sn = "result";
//                    String recevier = "4";
//                    String dispatcher = "6";
//                    String sign = "7";
//                    String strTime = "2016-09-06 23:20:20";
//
//                    FormBody formBody = new FormBody.Builder().add("sn", sn).add("recevier", recevier).add("dispatcher", dispatcher).add("sign", sign).add("strTime", strTime).build();
//                    okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(formBody).build();
//
//                    response = client.newCall(request).execute();
//                    if (response.isSuccessful()) {
//                        Toast.makeText(CommonScanActivity.this,"sucess",Toast.LENGTH_LONG).show();
//                        Log.v(Constant.TAG, "Success xlb");
//                    }else{
//                        Toast.makeText(CommonScanActivity.this,"error",Toast.LENGTH_LONG).show();
//                        Log.v(Constant.TAG, " xlb");
//                    }
//
//
//                } catch (Exception e) {
//                    Toast.makeText(CommonScanActivity.this,"error",Toast.LENGTH_LONG).show();
//                    e.printStackTrace();
//
//                }
//                response.close();
//            }
//        }).start();


//        new Thread(new Runnable() {
//            @Override
//            public void run() {
        String url = "http://myexpress2016.carp.mopaasapp.com/";
        url = url + actionName;
        Response response = null;

//                try{
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("sn", String.valueOf(sn))
                .add("peopleId", peopleId)
                .build();

        HttpClient.post(url, formBody, new HttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                Intent intent = new Intent(CommonScanActivity.this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("showToast", "1");
                bundle.putString("result", content);
                intent.putExtras(bundle);
                CommonScanActivity.this.startActivity(intent);
                finish();
            }

            @Override
            public void onFailure(Request request, IOException e) {
                Intent intent = new Intent(CommonScanActivity.this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("showToast", "2");
                intent.putExtras(bundle);
                CommonScanActivity.this.startActivity(intent);
                finish();
            }
        });


//                    Request request=new Request.Builder()
//                            .url(url)
//                            .post(formBody)
//                            .build();
//                     response=client.newCall(request).execute();
//                    if(response.isSuccessful()){
//                      //  System.out.println("express.debug,result="+response.body().toString());
//                        Intent intent=new Intent(CommonScanActivity.this,MainActivity.class);
//                        Bundle bundle=new Bundle();
//                        bundle.putString("showToast","1");
//                        intent.putExtras(bundle);
//                        CommonScanActivity.this.startActivity(intent);
//                        finish();
//                    }else{
//                        Intent intent=new Intent(CommonScanActivity.this,MainActivity.class);
//                        Bundle bundle=new Bundle();
//                        bundle.putString("showToast","2");
//                        intent.putExtras(bundle);
//                        CommonScanActivity.this.startActivity(intent);
//                        finish();
//                        System.out.println("express.debug,result=error");
//                    }
//                }catch(Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

    }

    void startScan() {
        if (rescan.getVisibility() == View.VISIBLE) {
            rescan.setVisibility(View.INVISIBLE);
            scan_image.setVisibility(View.GONE);
            scanManager.reScan();
        }
    }

    @Override
    public void scanError(Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        //相机扫描出错时
        if (e.getMessage() != null && e.getMessage().startsWith("相机")) {
            scanPreview.setVisibility(View.INVISIBLE);
        }
    }

    public void showPictures(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photo_path;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTOREQUESTCODE:
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(data.getData(), proj, null, null, null);
                    if (cursor.moveToFirst()) {
                        int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        photo_path = cursor.getString(colum_index);
                        if (photo_path == null) {
                            photo_path = Utils.getPath(getApplicationContext(), data.getData());
                        }
                        scanManager.scanningImage(photo_path);
                    }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.qrcode_g_gallery:
                showPictures(PHOTOREQUESTCODE);
                break;
            case R.id.iv_light:
                scanManager.switchLight();
                break;
            case R.id.qrcode_ic_back:
                finish();
                break;
            case R.id.service_register_rescan://再次开启扫描
                startScan();
                break;
            case R.id.authorize_return:
                finish();
                break;
            default:
                break;
        }
    }




}